var express = require('express');
var jwt = require('jsonwebtoken')
var router = express.Router();
var { landlordModel,
  houseModel,
  appointmentModel,
  questionModel,answerModel,collectModel,historyModel } = require('../model/model')

/* GET home page. */
router.get('/landlord',async(req,res)=>{
  let landlord = await landlordModel.find()
  res.send({
    code:200,
    msg:'landlordSuccess',
    landlord
  })
})

router.post('/landlordAdd',(req,res)=>{
  landlordModel.create(req.body)
  res.send({
    code:200,
    msg:'landlordAdd_success'
  })
})

router.get('/house',async(req,res)=>{
 
  let {page,pagesize,house_type}=req.query
  let house=[]
  let queryArr=[]
  let regType=new RegExp(house_type)
  if(house_type) queryArr.push({house_type:regType})
  if(queryArr.length!==0){
    house=await houseModel.find({$and:queryArr}).skip(page).limit(pagesize)
  }else{
    house=await houseModel.find().skip(page).limit(pagesize)
  }  
  res.send({house})
})

router.post('/upcollect',async(req,res)=>{
  let item=req.body
  console.log(item)
  await houseModel.updateOne({_id:item._id},{is_collect:!item.is_collect})
  if(item.is_collect===false){
    await collectModel.create(item)
  }else{
    await collectModel.deleteOne({_id:item._id})
  }
  res.send({
    code:200,
    msg:'更新成功'
  })
})

router.post('/houseAdd',(req,res)=>{
  houseModel.create(req.body)
  res.send({
    code:200,
    msg:'houseAdd_succssfully'
  })
})
//问题表
router.post('/questionAdd',(req,res)=>{
  questionModel.create(req.body)
  res.send({
    code:200,
    msg:'questionAdd_succssfully'
  })
})

router.get('/question',async(req,res)=>{
  
  let question=await questionModel.find()
  res.send({
    question
  })
})

router.post('/answerAdd',(req,res)=>{
  answerModel.create(req.body)
  res.send({
    code:200,
    msg:'answerAdd_succssfully'
  })
})

router.get('/answer',async(req,res)=>{
  let answer=await answerModel.find()
  // console.log(answer)
  res.send({
    answer
  })
})

//收藏表
router.get('/collect',async(req,res)=>{
  let collect=await collectModel.find()
  res.send({
    collect
  })
})

router.post('/collectadd',(req,res)=>{
  collectModel.create(req.body)
  res.send({
    code:200,
    msg:'collectAdd_succssfully'
  })
})

router.get('/history',async(req,res)=>{
  let history=await historyModel.find()
  res.send({
    history
  })
})

router.post('/historyadd',(req,res)=>{
  historyModel.create(req.body)
  res.send({
    code:200,
    msg:'historyAdd_succssfully'
  })
})

router.delete('/historydel/:_id',async(req,res)=>{
  let {_id}=req.params
  await historyModel.deleteOne({_id})
  res.send({
    code:200,
    msg:'historydel_succssfully'
  })
})
module.exports = router;
